﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Perovich.GameObjects.Interfaces;
using System.Reflection;
using Perovich.GameObjects.Components;

namespace Perovich.GameObjects.Entities
{
    public sealed class EntityFactory : Factory
    {

        public static T Create<T>(string name, ICanSupportComponents parent) where T : Entity
        {
            // if we didn't pass an object array, we would enter an infinite recursive loop
            // since we would essentially be calling this method, which then calls this method.. etc.
            // where we actually wanted to call the method overload taking an object[] parameter list
            return Create<T>(new object[] { name, parent });
        }

        public static T Create<T>(string name, ICanSupportComponents parent, params IEntityComponent[] components) where T : Entity
        {
            return Create<T>(new object[] { name, parent, components });
        }

        // all the code inside this method could be replaced by 1 line, if the CF hadn't stripped System.Activator down to a bare minimum
        private static T Create<T>(params object[] parameters) where T : Entity
        {
            ConstructorInfo bestMatch = GetBestMatchingConstructor(typeof(T), parameters);

            object o = null;

            try
            {
                o = bestMatch.Invoke(parameters);
            }
            catch (TargetInvocationException)
            {
                throw;
            }
            catch (TargetParameterCountException)
            {
                throw;
            }


            return o as T;
        }
    }
}
